﻿/*
____
 L|ypps Web controls for ASP.NET

Copyright (c) 2009 Alessandro Zifiglio, http://www.Typps.com
EMail: alessandro@Typps.com

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
namespace Typps
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web.UI;

    [Serializable]
    public class ElementPair
    {
        #region Fields

        List<string> attributesValue;
        string endTagValue = string.Empty;
        string startTagValue = string.Empty;

        #endregion Fields

        #region Properties

        public List<string> Attributes
        {
            get
            {
                if (attributesValue == null)
                    attributesValue = new List<string>();
                return attributesValue;
            }
        }

        public string EndTag
        {
            get { return endTagValue; } set { endTagValue = value; }
        }

        public string StartTag
        {
            get { return startTagValue; } set { startTagValue = value; }
        }

        #endregion Properties
    }

    public class HtmlStripper
    {
        #region Fields

        bool appendToEndElement = false;
        bool appendToStartElement = false;
        string attribute = string.Empty;
        List<string> attributes = null;
        bool beginAttribute = false;
        List<ElementPair> elements = null;
        bool endAttribute = false;
        string endTag = string.Empty;
        string lastChar = string.Empty;
        StripMode modeValue = StripMode.TagOnly;
        List<string> openElementsHierarchy = null;
        string startTag = string.Empty;
        bool stripContentNode = false;

        #endregion Fields

        #region Constructors

        public HtmlStripper(StripMode mode)
            : this(new List<ElementPair>(), mode)
        {
        }

        public HtmlStripper(List<ElementPair> elems, StripMode mode)
        {
            elements = elems;
            modeValue = mode;
        }

        #endregion Constructors

        #region Properties

        public StripMode Mode
        {
            get { return modeValue; }
        }

        #endregion Properties

        #region Methods

        public string Parse(char[] input)
        {
            if (openElementsHierarchy == null)
                openElementsHierarchy = new List<string>();
            if (attributes == null)
                attributes = new List<string>();

            StringBuilder output = new StringBuilder();
            int index = 0;
            /*
                HttpResponse filter is provided in chunks, so we could
                have been processing a style chunk or a script chunk last before
                we got cutoff to process a new chunk (which is merily a continuation
                of what we were doing last). So let's continue finishing pending tasks first.
             */
            for (int num1 = index; num1 < input.Length; num1++)
            {
                bool skip = false;
                char c = input[num1];

                string c1 = c.ToString();
                switch (c1)
                {
                    case "<":
                        if (!appendToStartElement)
                        {
                            startTag = c1;
                            appendToStartElement = true;
                            appendToEndElement = false;
                        }
                        else if (!appendToEndElement)
                        {
                            endTag = c1;
                            appendToEndElement = true;
                            appendToStartElement = false;
                        }
                        break;
                    case ">":
                        if (appendToStartElement)
                        {
                            if (beginAttribute)
                            {
                                endAttribute = true;
                                AppendAttribute(AttributePosition.End);
                            }
                            RenderAttributes();

                            startTag += c1;

                            if (startTag.IndexOf("/>") != -1)
                            {
                                // we have a self closing element without
                                // content, so we've reached the closing tag
                                appendToEndElement = false;
                            }
                            appendToStartElement = false;
                            bool isAllowedStartElement = IsAllowedStartElement(startTag);
                            if (isAllowedStartElement)
                                output.Append(startTag);

                            string openingTag = string.Format("<{0}>", ParseElementName(startTag));
                            openElementsHierarchy.Add(openingTag);

                            skip = true;
                        }
                        else if (appendToEndElement)
                        {
                            endTag += c1;
                            appendToEndElement = false;

                            bool isAllowedEndElement = IsAllowedEndElement(endTag);
                            if (ClosingElementMatchesStartTag(endTag))
                            {
                                if (isAllowedEndElement)
                                    output.Append(endTag);

                                if (openElementsHierarchy.Count > 0)
                                    openElementsHierarchy.RemoveAt(openElementsHierarchy.Count - 1);
                            }
                            skip = true;
                        }
                        break;
                    case "/":
                        if (lastChar == "<" && appendToStartElement)
                        {
                            appendToStartElement = false;
                            appendToEndElement = true;
                            endTag = startTag;
                        }
                        if (appendToEndElement)
                        {
                            endTag += c1;
                        }
                        else if (appendToStartElement)
                        {
                            RenderAttributes();
                            startTag += string.Format(" {0}", c1);
                        }
                        break;
                    default:
                        if (appendToStartElement)
                        {
                            if (IsNotNewElementStart(startTag))
                            {
                                appendToStartElement = false;
                                output.Append(startTag);
                            }
                            else
                            {
                                if (!beginAttribute && CharIsWhiteSpace(c))
                                    beginAttribute = true;
                                else if (beginAttribute && CharIsWhiteSpace(c))
                                    endAttribute = true;

                                if (beginAttribute)
                                    attribute += c1;
                                else
                                    startTag += c1;
                                AppendAttribute(AttributePosition.Begin);
                            }
                        }
                        else if (appendToEndElement)
                        {
                            endTag += c1;
                        }
                        if (openElementsHierarchy.Count > 0)
                        {
                            string lastElement = openElementsHierarchy[openElementsHierarchy.Count - 1];
                            if (!IsAllowedStartElement(lastElement) && Mode == StripMode.TagAndContent)
                                stripContentNode = true;
                            else
                                stripContentNode = false;
                        }
                        break;
                }
                if (((!appendToStartElement && !appendToEndElement) &&
                    !skip) && !stripContentNode)
                    output.Append(c);
                lastChar = c1;//in case we want to know the last char :-)
            }
            return output.ToString();
        }

        void AppendAttribute(AttributePosition position)
        {
            if (endAttribute)
            {
                string attributeName = ParseAttributeName(attribute);
                if (IsAllowedAttribute(startTag, attributeName))
                    attributes.Add(attribute.Trim());
                attribute = string.Empty;//reset
                if (position == AttributePosition.End)
                    beginAttribute = false;
                endAttribute = false;
            }
        }

        bool CharIsWhiteSpace(char c)
        {
            return char.IsWhiteSpace(c);
        }

        bool ClosingElementMatchesStartTag(string match)
        {
            /*
                find closing tag return to caller the correct one. in case it is wrong,
             * then the caller should be able to use the right closing tag and self close.
             */
            if (string.IsNullOrEmpty(match) || openElementsHierarchy.Count == 0) return false;
            string lastElem = openElementsHierarchy[openElementsHierarchy.Count - 1];
            string elementNameMatch = ParseElementName(match);
            string elementName = ParseElementName(lastElem);
            if (elementNameMatch.Equals(elementName, StringComparison.OrdinalIgnoreCase))
                return true;
            return false;
        }

        bool IsAllowedAttribute(string startTag, string attributeName)
        {
            if (string.IsNullOrEmpty(startTag) || string.IsNullOrEmpty(attributeName)) return false;
            foreach (ElementPair p in elements)
            {
                if (p.StartTag.StartsWith(startTag,
                        StringComparison.OrdinalIgnoreCase))
                {
                    foreach (string att in p.Attributes)
                    {
                        if (att.Equals(attributeName, StringComparison.OrdinalIgnoreCase))
                            return true;
                    }
                }
            }
            return false;
        }

        bool IsAllowedEndElement(string match)
        {
            if (string.IsNullOrEmpty(match)) return false;

            foreach (ElementPair p in elements)
            {
                if (p.EndTag.Equals(match,
                        StringComparison.OrdinalIgnoreCase))
                    return true;
            }
            return false;
        }

        bool IsAllowedStartElement(string match)
        {
            if (string.IsNullOrEmpty(match)) return false;
            if (match.IndexOf(' ') != -1)
                match = match.Split(' ')[0];
            foreach (ElementPair p in elements)
            {
                if (p.StartTag.StartsWith(match,
                        StringComparison.OrdinalIgnoreCase))
                    return true;
            }
            return false;
        }

        bool IsNotNewElementStart(string tag)
        {
            if (tag.StartsWith("<!"))
                return true;
            return false;
        }

        string ParseAttributeName(string value)
        {
            if (string.IsNullOrEmpty(value)) return string.Empty;
            string[] pairs = value.Split('=');
            return (pairs[0] ?? string.Empty).Trim();
        }

        string ParseElementName(string element)
        {
            string elementName = string.Empty;
            int startLen = 2;
            int start = element.IndexOf("</");
            if (start == -1)
            {
                startLen = 1;
                start = element.IndexOf("<");
            }
            if (start != -1)
            {
                int end = element.IndexOf(" ");
                if (end == -1)
                    end = element.IndexOf(">");
                if (end != -1)
                {
                    start += startLen;
                    elementName = element.Substring(start, end - start);
                }
            }
            return elementName;
        }

        void RenderAttributes()
        {
            if (attributes.Count > 0)
            {
                startTag = string.Format("{0} {1}", startTag.Trim(), string.Join(" ", attributes.ToArray()));
                attributes.Clear();
            }
        }

        #endregion Methods
    }
}